package com.hyf.rabbitmq.workQueue;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Worker2 {

    private static final String TASK_QUEUE_NAME="task_queue";
    public static void main(String[] args){
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setUsername("admin");
        factory.setPassword("12345");
        factory.setVirtualHost("/");
        factory.setPort(5672);
        Connection connection =null;
        Channel channel=null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();

            channel.queueDeclare(TASK_QUEUE_NAME,true,false,false,null);
            System.out.println("[*] waiting for message To exit press ");

            //每次从队列总获取数量
            channel.basicQos(1);

            final Channel finalChannel = channel;
            Consumer consumer=new DefaultConsumer(finalChannel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message=new String(body,"utf-8");
                    System.out.println(String.format("Worker2 [X] received %s",message));
                    try {
                        doWork(message);
                    }finally{
                        System.out.println("Worker2 [x] Done");
                        //消息处理完成ack确认
                        finalChannel.basicAck(envelope.getDeliveryTag(),false);
                    }
                }
            };
            channel.basicConsume(TASK_QUEUE_NAME,false,consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally{
            /*if(channel!=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
        }
    }

    //模拟处理任务
    private static void doWork(String task){
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
